import os
import argparse
import json

args = None

def get_auth():
	if args.auth!="":
		return "-i "+ args.auth
	else:
		return ""

def stop_mongod(infos):
	print "begin stop mongod..."
	for info in infos:
		cmd = 'mongo localhost:%d/admin --eval="db.shutdownServer({force: true})"'%(info["port"])
		fp = open("tmp_cmd", 'wt')
		fp.write(cmd)
		fp.close()
		os.system('plink %s %s@%s -m tmp_cmd'%( get_auth(), info["login_user"], info["host"]))
	print "stop mongod...[OK]"
	
def stop_config(infos):
	stop_mongod(infos)
	
def stop_mongos(infos):
	stop_mongod(infos)

if __name__ == "__main__":
	parser = argparse.ArgumentParser(description='rs_tool_stop',formatter_class=argparse.RawDescriptionHelpFormatter)
	parser.add_argument("--cfg", default="cfgs.json", help="cfg filename", type=str)
	parser.add_argument("--auth", default="", help="private key file for user authentication", type=str)
	args = parser.parse_args()
	
	fp = open(args.cfg, 'rt')
	jstr = fp.read()
	fp.close()
	jobj = json.loads(jstr)
	for k,v in jobj["replia_set"].items():
		stop_mongod(v)
	stop_config(jobj["config"])
	stop_mongos(jobj["mongos"])
	os.system('del /F /S /Q tmp_cmd')